<template>
  <contentModel
    v-if="modelValue"
    title="编辑"
    @close="cancel"
    @open="openModal"
  >
    <template #footer>
      <a-space>
        <a-button type="outline" @click="handleCancel(record, rowIndex)"
          >取消</a-button
        >
        <a-button
          type="primary"
          :loading="loading"
          @click="handleSubmit(record, rowIndex)"
          >保存</a-button
        >
      </a-space>
    </template>
    <a-form ref="formRef" :model="form" auto-label-width :rules="rules">
      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item label="逆向产品编号">
            {{ form.productReverseNo }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="故障单号">
            {{ form.failureFormNo }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="逆向类别">
            {{ form.scsProductReverseTypeName }}
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item label="计划执行状态">
            {{ form.planStatus }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="责任单位">
            {{ form.dutyDeptName }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="产品数量">
            {{ form.productQty }}
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item label="物料编码">
            {{ form.mdsItemCode }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="物料名称">
            {{ form.mdsItemName }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="故障品件号">
            {{ form.itemSerialNo }}
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item label="机型">
            {{ form.planModelType }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="型号">
            {{ form.marque }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="父型号">
            {{ form.cpParentModelCode }}
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item label="影响批次">
            {{ form.confineBatch }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="影响架次">
            {{ form.confineLot }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="故障内容信息">
            {{ form.failureContentInfo }}
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item label="实物外观状态">
            {{ form.appearanceStatus }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="实物配套状态">
            {{ form.equipStatus }}
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item
            v-if="pageModel === 2"
            field="failureFormInfo"
            label="故障单信息"
          >
            <a-input v-model="form.failureFormInfo" placeholder="请输入" />
          </a-form-item>
          <a-form-item v-else label="故障单信息">
            {{ form.failureFormInfo }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            v-if="pageModel === 2"
            field="mdsVendorCode"
            label="供应商"
          >
            <inputModal
              v-model="form.mdsVendorCode"
              :label-name="'supplierChinese'"
              :value-name="'supplierCode'"
              :label-value="form.mdsVendorName"
              :title="'供应商名称'"
              :type="'supplyName'"
              @handle-ok="selectSupplier"
            />
          </a-form-item>
          <a-form-item v-else label="供应商">
            {{ form.mdsVendorName }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            v-if="pageModel === 2"
            field="scsFeedbackState"
            label="返厂状态"
          >
            <dict-select
              v-model="form.scsFeedbackState"
              allow-clear
              dict-type="feedbackState"
              placeholder="请选择"
            ></dict-select>
          </a-form-item>
          <a-form-item v-else label="返厂状态">
            {{ form.scsFeedbackStateName }}
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item label="编制人">
            {{ form.editUserName }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="编制时间">
            {{ form.editTime }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="执行状态">
            {{ form.businessStatusName }}
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item label="实际返回时间">
            {{ form.realReturnTime }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="到货件号">
            {{ form.recievItemSerialNo }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="是否退款">
            {{ form.ynRefundName }}
          </a-form-item>
        </a-col>
      </a-row>
      <a-divider orientation="left">现场故障情况</a-divider>
      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item
            v-if="pageModel === 1"
            field="urgencyDegree"
            label="紧急程度"
          >
            <dict-select
              v-model="form.urgencyDegree"
              allow-clear
              dict-type="urgencyDegree"
              placeholder="请选择"
            ></dict-select>
          </a-form-item>
          <a-form-item v-else label="紧急程度">
            {{ form.urgencyDegreeName }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            v-if="pageModel === 1"
            field="wishReturnDate"
            label="期望返回时间"
          >
            <a-date-picker
              v-model="form.wishReturnDate"
              show-time
              style="width: 100%"
              :time-picker-props="{ defaultValue: '00:00:00' }"
              format="YYYY-MM-DD HH:mm:ss"
            />
          </a-form-item>
          <a-form-item v-else label="期望返回时间">
            {{ form.wishReturnDate }}
          </a-form-item>
        </a-col>
      </a-row>
      <a-divider orientation="left">排故信息编辑</a-divider>
      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item
            v-if="pageModel === 2"
            field="returnedFactoryDate"
            label="退厂时间"
          >
            <a-date-picker
              v-model="form.returnedFactoryDate"
              show-time
              style="width: 100%"
              :time-picker-props="{ defaultValue: '00:00:00' }"
              format="YYYY-MM-DD HH:mm:ss"
            />
          </a-form-item>
          <a-form-item v-else label="退厂时间">
            {{ form.returnedFactoryDate }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            v-if="pageModel === 2 || pageModel === 3"
            field="waybillInfo"
            label="运单编号"
          >
            <a-input v-model="form.waybillInfo" placeholder="请输入" />
          </a-form-item>
          <a-form-item v-else label="运单编号">
            {{ form.waybillInfo }}
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item v-if="pageModel === 2" field="solution" label="处理方式">
            <dict-select
              v-model="form.solution"
              allow-clear
              dict-type="solution"
              placeholder="请选择"
            ></dict-select>
          </a-form-item>
          <a-form-item v-else label="处理方式">
            {{ form.solutionName }}
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="16">
          <a-form-item label="质量证明文件">
            <a-checkbox-group
              v-model="hasList"
              :options="plainOptions"
              @change="changeCheckbox"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            v-if="pageModel === 2 || pageModel === 3"
            field="scsReturnedPurchaseMode"
            label="退厂方式"
          >
            <dict-select
              v-model="form.scsReturnedPurchaseMode"
              allow-clear
              dict-type="returnedPurchaseMode"
              placeholder="请选择"
            ></dict-select>
          </a-form-item>
          <a-form-item v-else label="退厂方式">
            {{ form.scsReturnedPurchaseModeName }}
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item v-if="pageModel === 2" label="备注">
            <a-textarea v-model="form.notes" placeholder="请输入" allow-clear />
          </a-form-item>
          <a-form-item v-else label="备注">
            {{ form.notes }}
          </a-form-item>
        </a-col>
      </a-row>
      <a-divider orientation="left">故障品信息跟踪</a-divider>
      <a-space v-if="pageModel === 3">
        <a-button type="primary" @click="addRow">新增</a-button>
      </a-space>
      <standard-table
        ref="detailTable"
        v-model:selectedKeys="detailSelectedKeys"
        :component-config="tableComponentConfig"
        :render-config="tableRenderConfig"
        :render-keys="tableRenderKeys"
        :loading="detailTableLoading"
        :data="detailTableData"
        :total="detailTableTotal"
        @init-columns-end="initColumns"
      >
        <template v-if="pageModel === 3" #operate="{ record, rowIndex }">
          <a-button type="text" @click="handleEdit(record, rowIndex)"
            >编辑</a-button
          >
          <a-button type="text" @click="handleDelete(record, rowIndex)"
            >删除</a-button
          >
        </template>
      </standard-table>
      <fileUpload
        v-model="fileValueList"
        multiple
        :show-file-list="true"
        :file-list="defaultList"
        btn-name="文件上传"
        btn-type="primary"
        accept=".xlsx,.pdf,.doc,.docx"
        title="供应商文件上传"
      />
      <!-- <a-space>
        <fileUpload
          v-model="fileValue"
          type="1"
          btn-name="文件上传"
          title="导入"
          accept=".xlsx,.pdf,.doc,.docx"
        />
        <div>
          <span>当前选中文件：</span>
          <span style="color: #165dff; cursor: pointer" @click="downloadFile"
            >{{ fileValue.name ? fileValue.name : '附件' }}
          </span>
        </div>
      </a-space> -->
    </a-form>
  </contentModel>
  <FaultInformationModal
    v-if="addModalVisible"
    v-model="addModalVisible"
    :select-id="selectRowId"
    :select-row="selectRow"
    @submit="addModalSubmit"
  />
</template>

<script lang="ts" setup>
  import { defineAsyncComponent, inject, reactive, ref, toRefs } from 'vue';
  import dictSelect from '@/common/components/dict-select/index.vue';
  import inputModal from '@/common/components/search-modal/input-modal.vue';
  import StandardTable from '@/common/components/standard-table/index.vue';
  import { Message } from '@arco-design/web-vue';
  import fileUpload from '@/common/components/file-upload-page/index.vue';
  import {
    updateScsProductDetail,
    getScsProductDetail,
    getScsProductReverseList,
  } from '@/api/reverse-procurement/product-handling';
  import FaultInformationModal from './fault-information-modal.vue';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from '../module-common/table-comp/base-table-config';

  const contentModel = defineAsyncComponent(
    () => import('@/common/components/content-model/index.vue')
  );
  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    // eslint-disable-next-line vue/require-prop-types
    selectId: {},
    pageModel: {
      type: Number,
      default: 1, // 1紧急程度维护_编辑 2排故信息编辑_编辑 3故障品情况跟踪_编辑
    },
  });
  const emits = defineEmits(['update:modelValue', 'fetchData']);
  const cancel = () => {
    emits('update:modelValue', false);
  };
  const { selectId, pageModel } = toRefs(props);
  // 当前表格要渲染哪些值
  const tableRenderKeys = [
    'situationTracking',
    'expectedReturnTime',
    'vendorEditUserName',
    'vendorEditDate',
    'operate',
  ];
  const plainOptions = ref([
    { label: '履历本', value: 'hasResumes' },
    { label: '合格证', value: 'hasCertificate' },
    { label: '装机证明', value: 'ynOriginalQualityDoc' },
  ]);
  // const { cancel } = useModelFun();
  const selectedRow = inject('selectedRow');
  const formRef = ref(null);
  const fileValueList = ref([]);
  const defaultList = ref([]);
  const hasList = ref([]);
  const loading = ref(false);
  const addModalVisible = ref(false);
  const selectRowIndex = ref(null);
  const selectRow = ref(null);
  const detailTableLoading = ref(false);
  const detailTableData = ref([]);
  const detailTableTotal = ref(0);
  const deleteProductReverseLVOList = ref([]);
  const form = reactive({});
  const rules = {
    // urgencyDegree: [
    //   {
    //     required: true,
    //     message: '紧急程度必填',
    //   },
    // ],
    // wishReturnDate: [
    //   {
    //     required: true,
    //     message: '期望返回时间必填',
    //   },
    // ],
    editDate: [
      {
        required: true,
        message: '登记日期必填',
      },
    ],
  };
  const changeCheckbox = (val) => {
    plainOptions.value.forEach((item) => {
      if (val.includes(item.value)) {
        form[item.value] = 1;
      } else {
        form[item.value] = 0;
      }
    });
  };
  const handleSubmit = async () => {
    form.iqsProveFile = JSON.stringify(fileValueList.value);
    const validate = await formRef.value.validate();
    if (validate) return;
    const formData = {
      ...form,
      productReverseLVOList: detailTableData.value.map((item) => {
        item.scsProductReverseId = selectId?.value;
        if (item.id.includes('id-')) {
          delete item.id;
        }
        return item;
      }),
      secretLevel: selectedRow?.value.secretLevel,
      deleteProductReverseLVOList: deleteProductReverseLVOList.value,
    };
    loading.value = true;
    await updateScsProductDetail(formData);
    Message.success({
      content: '编辑成功！',
      duration: 5 * 1000,
    });
    loading.value = false;
    emits('fetchData');
    cancel();
  };
  const addRow = () => {
    selectRow.value = {};
    addModalVisible.value = true;
  };
  const handleEdit = (row, index) => {
    selectRow.value = row;
    selectRowIndex.value = index;
    addModalVisible.value = true;
  };
  const handleDelete = (row, rowIndex) => {
    if (row.id && !row.id.includes('id-')) {
      deleteProductReverseLVOList.value.push(row);
    }
    detailTableData.value.splice(rowIndex, 1);
  };
  const addModalSubmit = (row) => {
    if (row.id) {
      detailTableData.value[selectRowIndex.value] = Object.assign(
        detailTableData.value[selectRowIndex.value],
        row
      );
    } else {
      detailTableData.value.push({
        ...row,
        id: `id-${new Date()}`,
      });
    }
    addModalVisible.value = false;
  };
  const handleCancel = () => {
    cancel();
  };
  const getDetailInfo = async () => {
    try {
      loading.value = true;
      const { data } = await getScsProductDetail(selectId?.value);
      plainOptions.value.forEach((item) => {
        if (Number(data[item.value]) === 1) {
          hasList.value.push(item.value);
        }
      });
      if (data.iqsProveFile) {
        try {
          defaultList.value = JSON.parse(data.iqsProveFile);
        } catch (error) {
          defaultList.value = [];
        }
      }
      Object.keys(data).forEach((key) => {
        form[key] = data[key];
      });
    } finally {
      loading.value = false;
    }
  };
  const getDetailTableList = async () => {
    // const page = detailTable.value.getStatus();
    detailTableLoading.value = true;
    const { data } = await getScsProductReverseList(selectId?.value);
    detailTableData.value = data || [];
    detailTableTotal.value = data.length;
    detailTableLoading.value = false;
  };
  const openModal = () => {
    if (loading.value) return;
    plainOptions.value = plainOptions.value.map((item) => {
      item.disabled = pageModel.value !== 2;
      return item;
    });
    if (selectId?.value) {
      loading.value = true;
      getDetailInfo();
      getDetailTableList();
    } else {
      loading.value = false;
    }
  };
</script>
